package com.ruoyi.system.api.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.JPushConfig;
import com.ruoyi.common.config.PushConfig;
import com.ruoyi.common.jpush.JPushClientUtil;
import com.ruoyi.common.utils.OkHttpUtils2;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.InstrumentInfo;
import com.ruoyi.system.api.domain.InterfaceOperationLog;
import com.ruoyi.system.api.domain.JpushLog;
import com.ruoyi.system.api.domain.PlanDetails;
import com.ruoyi.system.api.domain.ServiceDetails;
import com.ruoyi.system.api.domain.ServiceInstrument;
import com.ruoyi.system.api.domain.ServiceNotice;
import com.ruoyi.system.api.domain.ServicePart;
import com.ruoyi.system.api.domain.User;
import com.ruoyi.system.api.mapper.InstrumentInfoMapper;
import com.ruoyi.system.api.mapper.JpushLogMapper;
import com.ruoyi.system.api.mapper.PlanDetailsMapper;
import com.ruoyi.system.api.mapper.ServiceDetailsMapper;
import com.ruoyi.system.api.mapper.ServiceInstrumentMapper;
import com.ruoyi.system.api.mapper.ServiceNoticeMapper;
import com.ruoyi.system.api.mapper.ServicePartMapper;
import com.ruoyi.system.api.mapper.UserMapper;
import com.ruoyi.system.api.service.CcSyncDataService;
import com.ruoyi.system.api.service.IInterfaceOperationLogService;
import com.ruoyi.system.api.service.LocationService;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class CcSyncDataServiceImpl implements CcSyncDataService {

  private static final Logger log = LoggerFactory.getLogger(CcServiceImpl.class);

  /**
   * 配置文件
   */
  @Autowired
  private Global global;

  /**
   * 用户表
   */
  @Autowired
  private UserMapper userMapper;

  /**
   * 用户接口
   */
  @Autowired
  private UserServiceImpl userService;

  /**
   * 接口调用日志
   */
  @Autowired
  private IInterfaceOperationLogService iInterfaceOperationLogService;

  @Autowired
  private ServiceNoticeMapper serviceNoticeMapper;

  @Autowired
  private ServiceInstrumentMapper serviceInstrumentMapper;

  @Autowired
  private InstrumentInfoMapper instrumentInfoMapper;

  @Autowired
  private LocationService locationService;

  @Autowired
  private ServicePartMapper servicePartMapper;

  @Autowired
  private ServiceDetailsMapper serviceDetailsMapper;

  @Autowired
  private PlanDetailsMapper planDetailsMapper;

  @Autowired
  private JPushConfig jPushConfig;

  @Autowired
  private JpushLogMapper jpushLogMapper;

  @Override
  public ResponseWithData<?> syncServiceNotice(Long timeStamp) throws Exception {

    String ccServerUrl = global.getCcServerUrl();
    StringBuffer url = new StringBuffer();
    url.append(ccServerUrl);
    url.append("syncTLServiceData.asmx/GetNotificationInfo");

    /** POST请求 参数赋值 */
    FormBody.Builder builder = new FormBody.Builder();
    builder.add("last_sync_time", timeStamp.toString());

    /** 先保存接口参数 */
    InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
    interfaceOperationLog.setInterfaceName("2.2同步TL待指派服务信息接口");
    interfaceOperationLog.setInterfaceType("syncTLServiceData");
    interfaceOperationLog.setInterfaceUrl(url.toString());
    interfaceOperationLog.setStartTime(new Date());
    interfaceOperationLog.setInterfaceRequest(builder.toString());
    iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

    Response res = null;
    String interfaceResponse = "";
    String interfaceResponseBody = "";
    String interfaceState = "";
    try {

      /** 调用CC端接口 */
      //OkHttpUtils2  设置超时时间5分钟
      res = OkHttpUtils2.getInstance().postRequest(url.toString(), builder.build());
      interfaceResponse = res.toString();
      interfaceResponseBody = res.body().string();
      interfaceResponse += " Body参数：" + interfaceResponseBody;
      if (res.code() == 200) {
        interfaceState = "1";
      } else {
        interfaceState = "2";
      }
    } catch (Exception e) {
      log.error("调用CC接口异常：" + e.getMessage() + "," + interfaceResponseBody);
      interfaceResponse = e.getMessage();
      interfaceState = "0";

      return new ResponseWithData<>().error().msg("同步失败 调用CC端接口发生异常").code(201);
    }

    /** 更新接口返回结果 */
    interfaceOperationLog.setEndTime(new Date());
    interfaceOperationLog.setInterfaceResponse(interfaceResponse);
    interfaceOperationLog.setInterfaceState(interfaceState);
    iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

    if (res.code() == 200) {
      JSONObject obj = JSON.parseObject(interfaceResponseBody);
      if ("1".equals(obj.getString("status"))) {

        /** 获取CC端 */
        JSONArray jsonArray = obj.getJSONArray("record");
        if (jsonArray != null && jsonArray.size() > 0) {
          for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            //解析同步过来的数据
            ServiceNotice serviceNotice = parseServiceNoticeRd(jsonObject);

            // 更新服务状态
            if ("TL派单".equals(serviceNotice.getServiceStatus())) {
              serviceNotice.setAppState(1L);//待派单
            }
            else if ("已派单".equals(serviceNotice.getServiceStatus())) {
            }
            else if ("保留".equals(serviceNotice.getServiceStatus())) {
            }
            else if ("已完成".equals(serviceNotice.getServiceStatus())) {
              //服务状态是已完成的修改服务单状态为已完成
              serviceNotice.setAppState(3L);//已完成 已关闭
            }
            if(StringUtils.equals("撤单",serviceNotice.getServiceStatus())){
              if(ObjectUtils.isEmpty(serviceNotice.getUpdateDate())){
                serviceNotice.setUpdateDate(new Date());
              }
            }
            /** 通过服务号验证数据库中是否存在 */
            ServiceNotice serviceNoticeOld = selectServiceNoticeByServieNo(serviceNotice.getServiceNo());

            if (serviceNoticeOld != null ) {
              serviceNotice.setId(serviceNoticeOld.getId());

              /** 服务单主表 如果存在更新 更新cc过来的数据*/
              serviceNoticeMapper.updateSyncServiceNotice(serviceNotice);
            }
            else {
              // 新增 服务单数据
              serviceNotice.setAppState(1L);
              serviceNotice.setRecordTime(new Date());
              serviceNoticeMapper.insertServiceNotice(serviceNotice);
            }

            //派单处理  TL派单发送消息提醒
            if ("TL派单".equals(serviceNotice.getServiceStatus())) {
              dealServiceNoticeTLPaiDan(serviceNotice);
            }

            //FSE派单 处理（TL重新派单，原有FSE任务保留，删除状态）
            dealServiceNoticeFSEPaiDan(serviceNotice);

            // 仪器信息
            String instrument_data = jsonObject.getString("instrument_data");
            parseAndUpdateServiceNoticeInstrument(serviceNotice, instrument_data);

            // 备件信息
            String Part_data = jsonObject.getString("Part_data");
            parseAndUpdateServiceNoticePart(serviceNotice, Part_data);

            //更新服务状态
            updateServiceStatus(serviceNotice, serviceNoticeOld);
          }
        }
        return new ResponseWithData().success().msg("同步成功").code(200);
      } else if ("2".equals(obj.getString("status"))) {
        //无数据
        return new ResponseWithData().success().msg("同步成功").code(200);
      }
    }

    return new ResponseWithData<>().error().msg("同步失败").code(201);
  }

  /**
   * 更新服务状态
   * @param serviceNotice
   * @param serviceNoticeOld
   */
  private void updateServiceStatus(ServiceNotice serviceNotice, ServiceNotice serviceNoticeOld) {
    // 现在同步过来是【保留】状态 直接修改服务单为保留状态     AppIsAccept 1 ——CC操作APP不显示
    if ("保留".equals(serviceNotice.getServiceStatus()) || "1".equals(serviceNotice.getAppIsAccept())) {
      ServiceNotice serviceNoticeUpdateFlag = new ServiceNotice();
      serviceNoticeUpdateFlag.setServiceNo(serviceNotice.getServiceNo());
      serviceNoticeUpdateFlag.setDelFlag("2");
      serviceNoticeMapper.updateServiceNotice(serviceNoticeUpdateFlag);

      //更新service_detail 记录保留
      ServiceDetails serviceDetails2 = new ServiceDetails();
      serviceDetails2.setDelFlag("2");
      serviceDetails2.setServiceNo(serviceNotice.getServiceNo());
      //serviceDetails2.setFseId(serviceDetails1.get(b).getFseId());
      //serviceDetails2.setState(0L);//不修改状态，如果修改状态，保留后再恢复 状态不能继续
      serviceDetailsMapper.updateDelServiceDetails(serviceDetails2);

      //PlanDetails 保留
      PlanDetails planDetails2 = new PlanDetails();
      planDetails2.setDelFlag("2");
      planDetails2.setServiceNo(serviceNotice.getServiceNo());
      //planDetails2.setFseId(serviceDetails1.get(b).getFseId());
      //planDetails2.setState("0");//不修改状态，如果修改状态，保留后再恢复 状态不能继续
      planDetailsMapper.updateDelPlanDetail(planDetails2);
    }
    else {
        // 如果之前这条数据是保留数据
        if (serviceNoticeOld!=null && "2".equals(serviceNoticeOld.getDelFlag())) {
          ServiceNotice serviceNoticeUpdateFlag = new ServiceNotice();
          serviceNoticeUpdateFlag.setServiceNo(serviceNotice.getServiceNo());
          // 现在同步过来不是保留状态 则解除保留
          serviceNoticeUpdateFlag.setDelFlag("0");
          serviceNoticeMapper.updateServiceNotice(serviceNoticeUpdateFlag);
        }
    }
  }

  /**
   * 给tl发送 待派工消息推送
   * @param serviceNotice
   */
  private void dealServiceNoticeTLPaiDan(ServiceNotice serviceNotice) {

    //推送待派工消息
    if (StringUtils.isNotEmpty(serviceNotice.getTeamleaderId())) {
      User user1 = new User();
      user1.setEnginnerId(Long.parseLong(serviceNotice.getTeamleaderId()));
      List<User> users1 = userMapper.selectUserList(user1);
      if (users1 != null && users1.size() > 0 && StringUtils
          .isNotEmpty(users1.get(0).getRegistrationId())) {

        // 如果是TL派单 给TL发送推送
        if ("TL派单".equals(serviceNotice.getServiceStatus())) {
          // 调用TL推送
          this.pushTeamleader(serviceNotice.getId() + "", serviceNotice.getServiceNo(), serviceNotice.getTeamleaderId(),
              users1.get(0).getRegistrationId());
        }
      }
    }
  }

  /**
   * 同步派单数据处理
   * 如果fse 为空 更新service_detail、PlanDetails保留状态
   * @param serviceNotice
   */
  private void dealServiceNoticeFSEPaiDan(ServiceNotice serviceNotice) {
    // 如果数据库存在此服务单，而且新同步过来的状态是“已派单” 需要比对 FSE，缺少的移除，新增的添加，原有删除的回复正常，原有非删除不变
    if (StringUtils.isNotEmpty(serviceNotice.getFse())) {

      ServiceNotice serviceNoticeOld = selectServiceNoticeByServieNo(serviceNotice.getServiceNo());
      User teamLeader = userService.selectUserByEnginnerId(serviceNotice.getTeamleaderId());

      //是否推送消息
      boolean canPushMsg = true;
      if ("保留".equals(serviceNotice.getServiceStatus()) || "1"
          .equals(serviceNotice.getAppIsAccept())) {
        canPushMsg = false;
      }

      String[] Fses = serviceNotice.getFse().split(",");
      if (Fses != null && Fses.length > 0) {
        // 查询数据库中已经派过人的数据 并且是未删除的数据
        ServiceDetails serviceDetails = new ServiceDetails();
        serviceDetails.setServiceNo(serviceNotice.getServiceNo());
        // serviceDetails.setDelFlag("0");//限定后，数据无法恢复？？？
        List<ServiceDetails> serviceDetails1 = serviceDetailsMapper
            .selectServiceDetailsList(serviceDetails);
        // 需要比对
        if (serviceDetails1 != null && serviceDetails1.size() > 0) {
          // 新增数据
          List<String> yList = new ArrayList();
          // 删除数据
          List<String> nList = new ArrayList();

          // 找到需要新增的数据
          for (int a = 0; a < Fses.length; a++) {
            boolean sign = false;
            for (int b = 0; b < serviceDetails1.size(); b++) {
              if (Fses[a].equals(serviceDetails1.get(b).getFseId())) {
                sign = true;
                break;
              }
            }
            // 如果没有相同的就是新增的
            if (!sign) {
              yList.add(Fses[a]);
            }
          }

          // 找到需要删除的数据
          for (int a = 0; a < serviceDetails1.size(); a++) {
            boolean sign = false;
            for (int b = 0; b < Fses.length; b++) {
              if (serviceDetails1.get(a).getFseId().equals(Fses[b])) {
                sign = true;
                break;
              }
            }
            if (!sign) {
              nList.add(serviceDetails1.get(a).getFseId());
            }
          }

          //1、本地存在，更新状态为【正常】
          ServiceDetails serviceDetailsOld;
          for (int a = 0; a < Fses.length; a++) {
            for (int b = 0; b < serviceDetails1.size(); b++) {
              serviceDetailsOld = serviceDetails1.get(b);
              if (Fses[a].equals(serviceDetailsOld.getFseId())) {

                ServiceDetails serviceDetails2 = new ServiceDetails();
                serviceDetails2.setDelFlag("0");
                serviceDetails2.setServiceNo(serviceNotice.getServiceNo());
                serviceDetails2.setFseId(serviceDetailsOld.getFseId());
                //如果原来是已拒绝6 更新为待接受状态 0
                if (serviceDetailsOld.getState()==6L) {
                  serviceDetails2.setState(0L);
                }
                serviceDetailsMapper.updateDelServiceDetails(serviceDetails2);

                PlanDetails planDetails2 = new PlanDetails();
                planDetails2.setDelFlag("0");
                planDetails2.setServiceNo(serviceNotice.getServiceNo());
                planDetails2.setFseId(serviceDetailsOld.getFseId());
                //如果原来是已拒绝6 更新为待接受状态 0
                if (serviceDetailsOld.getState()==6L) {
                  planDetails2.setState("0");
                  planDetails2.setIsAccept("2");
                }
                planDetailsMapper.updateDelPlanDetail(planDetails2);

                if (serviceDetailsOld.getState()==6L || "2".equals(serviceDetailsOld.getDelFlag())) {
                  //发送提醒
                  if (canPushMsg) {
                    try {
                      User usersFse = userService.selectUserByEnginnerId(Fses[a]);
                      if (usersFse != null) {
                        PlanDetails planDetails = selectPlanDetailByServiceNoAndFseId(
                            serviceNoticeOld.getServiceNo(), usersFse.getEnginnerId().toString());

                        // TODO 如果推送标识有值 推送给TL
                        if (StringUtils.isNotEmpty(teamLeader.getName()) &&
                            usersFse != null && planDetails != null &&
                            StringUtils.isNotEmpty(usersFse.getRegistrationId())) {
                          // fse 待接受推送
                          this.pushDaiJieShou(serviceNoticeOld.getId().toString(),
                              serviceNoticeOld.getServiceNo(),
                              usersFse.getEnginnerId().toString(),
                              usersFse.getRegistrationId(),
                              planDetails.getId() + "", teamLeader.getName());
                        }
                      }
                    }
                    catch (Exception e){
                      log.error(e.getMessage());
                    }
                  }
                }
              }
            }
          }

          //2、操作新增数据
          if (yList != null && yList.size() > 0) {
            // 如果有TL推送，没有不推送
            if (StringUtils.isNotEmpty(serviceNotice.getTeamleaderId())) {
              User user1 = new User();
              user1.setEnginnerId(Long.parseLong(serviceNotice.getTeamleaderId()));
              List<User> users1 = userMapper.selectUserList(user1);
              if (users1 != null && users1.size() > 0 && StringUtils
                  .isNotEmpty(users1.get(0).getName())) {
                // 调用保存待指派数据方法
                this.insertDaiZhiPai(null, yList, serviceNotice.getId() + "",
                    serviceNotice.getServiceNo(),
                    users1.get(0).getName(), canPushMsg);
              }
              // 如果没有不推送
              else {
                // 调用保存待指派数据方法
                this.insertDaiZhiPai(null, yList, serviceNotice.getId() + "",
                    serviceNotice.getServiceNo(),
                    null, canPushMsg);
              }
            }
            // 没有Tl不推送
            else {
              // 调用保存待指派数据方法
              this.insertDaiZhiPai(null, yList, serviceNotice.getId() + "",
                  serviceNotice.getServiceNo(),
                  null, canPushMsg);
            }
          }

          //3、操作删除数据
          if (nList != null && nList.size() > 0) {
            for (String s : nList) {
              ServiceDetails serviceDetails2 = new ServiceDetails();
              serviceDetails2.setDelFlag("2");
              serviceDetails2.setServiceNo(serviceNotice.getServiceNo());
              serviceDetails2.setFseId(s);
              //serviceDetails2.setState(0L);//不修改状态，如果修改状态，保留后再恢复 状态不能继续
              serviceDetailsMapper.updateDelServiceDetails(serviceDetails2);

              PlanDetails planDetails2 = new PlanDetails();
              planDetails2.setDelFlag("2");
              planDetails2.setServiceNo(serviceNotice.getServiceNo());
              planDetails2.setFseId(s);
              //planDetails2.setState("0");//不修改状态，如果修改状态，保留后再恢复 状态不能继续
              planDetailsMapper.updateDelPlanDetail(planDetails2);
            }
          }
        }
        // 不需要比对
        else {
          // 都是新增 直接入库
          if (StringUtils.isNotEmpty(serviceNotice.getTeamleaderId())) {
            User user1 = new User();
            user1.setEnginnerId(Long.parseLong(serviceNotice.getTeamleaderId()));
            List<User> users1 = userMapper.selectUserList(user1);
            if (users1 != null && users1.size() > 0 && StringUtils
                .isNotEmpty(users1.get(0).getName())) {
              // 调用保存待指派数据方法
              this.insertDaiZhiPai(Fses, null, serviceNotice.getId() + "",
                  serviceNotice.getServiceNo(),
                  users1.get(0).getName(), canPushMsg);
            }
            // 如果没有不推送
            else {
              // 调用保存待指派数据方法
              this.insertDaiZhiPai(Fses, null, serviceNotice.getId() + "",
                  serviceNotice.getServiceNo(),
                  null, canPushMsg);
            }
          }
          // 没有Tl不推送
          else {
            // 调用保存待指派数据方法
            this.insertDaiZhiPai(Fses, null, serviceNotice.getId() + "",
                serviceNotice.getServiceNo(),
                null, canPushMsg);
          }
        }
      }
    }
    else {
      // 如果fse 为空 更新service_detail、PlanDetails保留状态
      //更新service_detail 记录保留
      ServiceDetails serviceDetails2 = new ServiceDetails();
      serviceDetails2.setDelFlag("2");
      serviceDetails2.setServiceNo(serviceNotice.getServiceNo());
      //serviceDetails2.setFseId(serviceDetails1.get(b).getFseId());
      //serviceDetails2.setState(0L);//不修改状态，如果修改状态，保留后再恢复 状态不能继续
      serviceDetailsMapper.updateDelServiceDetails(serviceDetails2);

      //PlanDetails 保留
      PlanDetails planDetails2 = new PlanDetails();
      planDetails2.setDelFlag("2");
      planDetails2.setServiceNo(serviceNotice.getServiceNo());
      //planDetails2.setFseId(serviceDetails1.get(b).getFseId());
      //planDetails2.setState("0");//不修改状态，如果修改状态，保留后再恢复 状态不能继续
      planDetailsMapper.updateDelPlanDetail(planDetails2);
    }
  }

  private PlanDetails selectPlanDetailByServiceNoAndFseId(String serviceNo, String fseid){
    PlanDetails planDetails = new PlanDetails();
    planDetails.setServiceNo(serviceNo);
    planDetails.setFseId(fseid);
    List<PlanDetails> planDetailsLst = planDetailsMapper.selectStPlanDetailsList(planDetails);
    if(planDetailsLst!=null && planDetailsLst.size()>0) {
      return planDetailsLst.get(0);
    }

    return null;
  }

  private ServiceNotice selectServiceNoticeByServieNo(String serviceNo){
    ServiceNotice serviceNotice = new ServiceNotice();
    serviceNotice.setServiceNo(serviceNo);
    List<ServiceNotice> serviceNoticeList = serviceNoticeMapper.selectServiceNoticeList(serviceNotice);
    if(serviceNoticeList!=null && serviceNoticeList.size()>0){
      return serviceNoticeList.get(0);
    }
    return null;
  }

  private ServiceNotice parseServiceNoticeRd(JSONObject jsonObject) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    ServiceNotice serviceNotice = new ServiceNotice();

    // Service号
    String service_no = jsonObject.getString("service_no");
    serviceNotice.setServiceNo(service_no);

    // 服务状态
    String service_status = jsonObject.getString("service_status");
    serviceNotice.setServiceStatus(service_status);

    // Teamleader
    String teamleader = jsonObject.getString("teamleader");
    if (StringUtils.isNotEmpty(teamleader)) {
      serviceNotice.setTeamleaderId(teamleader);
    }

    // 已派单工程师
    String Fse = jsonObject.getString("Fse") == null ? "" : jsonObject.getString("Fse");
    if (StringUtils.isNotEmpty(Fse)) {
      serviceNotice.setFse(Fse);
    }

    //1 ——CC操作APP不显示0——APP显示
    String AppIsAccept = jsonObject.getString("AppIsAccept");
    serviceNotice.setAppIsAccept(AppIsAccept);



    // 联系人
    String contact = jsonObject.getString("contact");
    serviceNotice.setContact(contact);

    // 用户名称
    String customer_name = jsonObject.getString("customer_name");
    serviceNotice.setCustomerName(customer_name);

    // 用户英文名称
    String customer_enname = jsonObject.getString("customer_enname");
    serviceNotice.setCustomerEnname(customer_enname);

    // 电话
    String telephone = jsonObject.getString("telephone");
    serviceNotice.setTelephone(telephone);

    // 客户类型
    String enginner_type = jsonObject.getString("enginner_type");
    serviceNotice.setEnginnerType(enginner_type);

    // 客户类型
    String userIsDpel = jsonObject.getString("User_IsDpel");
    serviceNotice.setUserIsdpel(userIsDpel);

    // 手机
    String mobile = jsonObject.getString("mobile");
    serviceNotice.setMobile(mobile);

    // 电子邮件
    String email = jsonObject.getString("email");
    serviceNotice.setEmail(email);

    // 省份
    String province = jsonObject.getString("province");
    serviceNotice.setProvince(province);

    // 服务合同
    String service_contract = jsonObject.getString("service_contract") == null ? ""
        : jsonObject.getString("service_contract");
    serviceNotice.setServiceContract(service_contract);

    // 城市
    String city = jsonObject.getString("city");
    serviceNotice.setCity(city);

    // 希望服务时间
    String hope_business_hours = jsonObject.getString("hope_business_hours");
    if (StringUtils.isNotEmpty(hope_business_hours)) {
      if (hope_business_hours.length() == 10) {
        hope_business_hours += " 00:00:00";
      }
      serviceNotice.setHopeBusinessHours(sdf.parse(hope_business_hours));
    }

    // 上门地址
    String home_address = jsonObject.getString("home_address");
    serviceNotice.setHomeAddress(home_address);

    // 完备日期
    String MaturityDate = jsonObject.getString("MaturityDate");
    if(MaturityDate==null) {
    	serviceNotice.setMaturityDate(null);
    }else {
    	 serviceNotice.setMaturityDate(sdf.parse(MaturityDate));
    }
   

    // 服务类型
    String service_type = jsonObject.getString("service_type");
    serviceNotice.setServiceType(service_type);

    // 子服务类型
    String sub_service_type = jsonObject.getString("sub_service_type") == null ? ""
        : jsonObject.getString("sub_service_type");
    serviceNotice.setSubServiceType(sub_service_type);

    // 服务级别
    String service_level = jsonObject.getString("service_level");
    serviceNotice.setServiceLevel(service_level);

    // 安装准备确认单
    String install_confirm_sheet = jsonObject.getString("install_confirm_sheet");
    serviceNotice.setInstallConfirmSheet(install_confirm_sheet);

    // 生成时间
    String create_time = jsonObject.getString("create_time");
    serviceNotice.setCreateTime(sdf.parse(create_time));

    // 是否保内
    String is_warranty = jsonObject.getString("is_warranty");
    serviceNotice.setIsWarranty(is_warranty);

    // 邮编
    String postCode = jsonObject.getString("POSTCODE");
    serviceNotice.setPostCode(postCode);

    // 距离上次服务关闭时间
    Long last_colse_service_time = jsonObject.getLong("last_colse_service_time");
    if (last_colse_service_time != null) {
      serviceNotice.setLastColseServiceTime(last_colse_service_time);
    }

    // 仪器最后服务关闭时间
    String machine_last_service_colse_time =
        jsonObject.getString("machine_last_service_colse_time") == null ? ""
            : jsonObject.getString("machine_last_service_colse_time");
    if (StringUtils.isNotEmpty(machine_last_service_colse_time)) {
      serviceNotice
          .setMachineLastServiceColseTime(sdf.parse(machine_last_service_colse_time));
    }

    // 派单人
    String send_service = jsonObject.getString("send_service");
    serviceNotice.setSendService(send_service);

    // 派单时间
    String Send_time =
        jsonObject.getString("Send_time") == null ? "" : jsonObject.getString("Send_time");
    if (StringUtils.isNotEmpty(Send_time)) {
      if (Send_time.length() == 10) {
        Send_time += " 00:00:00";
      }
      serviceNotice.setSendTime(sdf.parse(Send_time));
    }

    // 故障描述
    String trouble_description = jsonObject.getString("trouble_description");
    serviceNotice.setTroubleDescription(trouble_description);

    // 备注
    String remark = jsonObject.getString("remark");
    serviceNotice.setRemark(remark);

    // 客户VIP标识
    String is_vip = jsonObject.getString("is_vip");
    serviceNotice.setIsVip(is_vip);

    // 接待人
    String receiver =
        jsonObject.getString("receiver") == null ? "" : jsonObject.getString("receiver");
    serviceNotice.setReceiver(receiver);

    // 接待人手机
    String receiver_mobile = jsonObject.getString("receiver_mobile") == null ? ""
        : jsonObject.getString("receiver_mobile");
    serviceNotice.setReceiverMobile(receiver_mobile);

    // 接待人邮箱
    String receiver_email = jsonObject.getString("receiver_email") == null ? ""
        : jsonObject.getString("receiver_email");
    serviceNotice.setReceiverEmail(receiver_email);


    // 电脑厂家
    String computer_Mfr = jsonObject.getString("computer_Mfr");
    serviceNotice.setComputerMfr(computer_Mfr);

    // 电脑型号
    String model_number = jsonObject.getString("model_number");
    serviceNotice.setModelNumber(model_number);

    // 服务号
    String service_number = jsonObject.getString("service_number");
    serviceNotice.setServiceNumber(service_number);

    // 操作系统
    String software = jsonObject.getString("software");
    serviceNotice.setSoftware(software);

    // 选项软件
    String option_software = jsonObject.getString("option_software");
    serviceNotice.setOptionSoftware(option_software);

    // 系统软件
    String system_software = jsonObject.getString("system_software");
    serviceNotice.setSystemSoftware(system_software);

    // 培训名额
    String train_quota = jsonObject.getString("train_quota");
    serviceNotice.setTrainQuota(train_quota);

    // 仪器类型
    String producttype = jsonObject.getString("producttype") == null ? ""
        : jsonObject.getString("producttype");
    serviceNotice.setProducttype(producttype);

    // 合同信息
    String contract_info = jsonObject.getString("contract_info");
    serviceNotice.setContractInfo(contract_info);

    // TODO arrive_time、service_enginner、appoint_time 字段接口文档中没有 返回值有

    // 服务关闭时间
    String close_time = jsonObject.getString("close_time");
    if (StringUtils.isNotEmpty(close_time)) {
      if (close_time.length() == 16) {
        close_time += ":00";
      }
      serviceNotice.setCloseTime(sdf.parse(close_time));
    }

    // 仪器安装时间
    String installation_date = jsonObject.getString("installation_date");
    if (StringUtils.isNotEmpty(installation_date)) {
      if (installation_date.length() == 10) {
        installation_date += " 00:00:00";
      }
      serviceNotice.setInstallationDate(sdf.parse(installation_date));
    }

    // CFDA
    String CFDA = jsonObject.getString("CFDA");
    serviceNotice.setCfda(CFDA);


    //AppRemark APP不可操作原因
    String AppRemark = jsonObject.getString("AppRemark");
    serviceNotice.setAppRemark(AppRemark);

    //SAP服务号
    String Sap_SnNO = jsonObject.getString("Sap_SnNO");
    serviceNotice.setSapSnno(Sap_SnNO);

    //指定工程师
    String designEngineer = jsonObject.getString("DesignEngineer");
    serviceNotice.setDesignEngineer(designEngineer);
    
    //工程师姓名
    String serviceEnginner = jsonObject.getString("service_enginner");
    serviceNotice.setServiceEnginner(serviceEnginner);;
    

    // 仪器信息 需要处理
    String instrument_data = jsonObject.getString("instrument_data");
    if (StringUtils.isNotEmpty(instrument_data) && !"[]".equals(instrument_data)) {
      // TODO 解析仪器信息
      JSONObject instrument_data_json = JSON.parseArray(instrument_data).getJSONObject(0);

      // AcountFSE
      String AcountFSE = instrument_data_json.getString("AcountFSE") == null ? ""
          : instrument_data_json.getString("AcountFSE");
      serviceNotice.setAccoutfseId(AcountFSE);

      // AcountName
      String acountName = instrument_data_json.getString("AcountName") == null ? ""
          : instrument_data_json.getString("AcountName");
      serviceNotice.setAccoutfseName(acountName);

    }

    return serviceNotice;
  }

  private void parseAndUpdateServiceNoticeInstrument(ServiceNotice serviceNotice, String instrument_data) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    if (StringUtils.isNotEmpty(instrument_data) && !"[]".equals(instrument_data)) {
      // TODO 解析仪器信息
      JSONObject instrument_data_json = JSON.parseArray(instrument_data).getJSONObject(0);

      /** 关联服务单的仪器表 */
      ServiceInstrument serviceInstrument = new ServiceInstrument();
      /** 仪器表 */
      InstrumentInfo instrumentInfo = new InstrumentInfo();

      serviceInstrument.setServiceNoticeId(serviceNotice.getId());
      serviceInstrument.setServiceNo(serviceNotice.getServiceNo());

      List<ServiceInstrument> serviceInstrumentList = serviceInstrumentMapper
          .selectServiceInstrumentList(serviceInstrument);

      // 仪器id
      String instrument_id = instrument_data_json.getString("instrument_id");
      serviceInstrument.setInstrumentId(instrument_id);
      instrumentInfo.setInstrumentId(instrument_id);

      List<InstrumentInfo> instrumentInfoList = instrumentInfoMapper
          .selectInstrumentInfoList(instrumentInfo);

      // 仪器型号
      String instrument_no = instrument_data_json.getString("instrument_no");
      serviceInstrument.setInstrumentNo(instrument_no);

      // 仪器序列号
      String instrument_serial_number = instrument_data_json
          .getString("instrument_serial_number");
      serviceInstrument.setInstrumentSerialNumber(instrument_serial_number);
      instrumentInfo.setInstSn(instrument_serial_number);

      // factory So
      String factory_so = instrument_data_json.getString("factory_so");
      serviceInstrument.setFactorySo(factory_so);

      // 发货时间
      String delivery_time = instrument_data_json.getString("delivery_time");
      if (StringUtils.isNotEmpty(delivery_time)) {
        serviceInstrument.setDeliveryTime(sdf.parse(delivery_time));
      }

      // 保修开始时间
      String guarantee_start_time = instrument_data_json.getString("guarantee_start_time");
      if (StringUtils.isNotEmpty(guarantee_start_time)) {
        serviceInstrument.setGuaranteeStartTime(sdf.parse(guarantee_start_time));
      }

      // 保修结束时间
      String guarantee_end_time = instrument_data_json.getString("guarantee_end_time");
      if (StringUtils.isNotEmpty(guarantee_end_time)) {
        serviceInstrument.setGuaranteeEndTime(sdf.parse(guarantee_end_time));
      }

      // 合同
      String contract = instrument_data_json.getString("contract");
      serviceInstrument.setContract(contract);

      // 备件
      String part = instrument_data_json.getString("part");
      serviceInstrument.setPart(part);

      // SLA
      String sla = instrument_data_json.getString("sla") == null ? ""
          : instrument_data_json.getString("sla");
      serviceInstrument.setSla(sla);

      // 备注
      String instrument_remark = instrument_data_json.getString("instrument_remark");
      serviceInstrument.setInstrumentRemark(instrument_remark);

      // 仪器类型
      String instrument_type = instrument_data_json.getString("instrument_type");
      serviceInstrument.setInstrumentType(instrument_type);

      // 仪器状态
      String instrument_status = instrument_data_json.getString("instrument_status");
      serviceInstrument.setInstrumentStatus(instrument_status);

      // 状态备注
      String Status_remark = instrument_data_json.getString("Status_remark");
      serviceInstrument.setStatusRemark(Status_remark);

      // Materialcode
      String Materialcode = instrument_data_json.getString("Materialcode");
      serviceInstrument.setMaterialcode(Materialcode);

      // lifecycle
      String lifecycle = instrument_data_json.getString("lifecycle");
      serviceInstrument.setLifecycle(lifecycle);

      // 品牌
      String brand = instrument_data_json.getString("Brand");
      serviceInstrument.setBrand(brand);

      // 约定服务范围
      String ServiceRange = instrument_data_json.getString("ServiceRange");
      serviceInstrument.setServiceRange(ServiceRange);

      // DEVI-BU
      String divi_bu = instrument_data_json.getString("divi_bu");
      serviceInstrument.setDiviBu(divi_bu);

      // 安装地址
      String InsAddress = instrument_data_json.getString("InsAddress");
      instrumentInfo.setInstAddress(InsAddress);

      // MD标识
      String mdsign = instrument_data_json.getString("mdsign");
      serviceInstrument.setMdsign(mdsign);

      // 验收报告需求
      String acceptrequest = instrument_data_json.getString("acceptrequest") == null ? ""
          : instrument_data_json.getString("acceptrequest");
      serviceInstrument.setAcceptrequest(acceptrequest);

      // MD标识
      String sap_material_no =
          instrument_data_json.getString("sap_material_no") == null ? ""
              : instrument_data_json.getString("sap_material_no");
      serviceInstrument.setSapMaterialNo(sap_material_no);

      // AcountFSE
      String AcountFSE = instrument_data_json.getString("AcountFSE") == null ? ""
          : instrument_data_json.getString("AcountFSE");
      serviceNotice.setAccoutfseId(AcountFSE);
      instrumentInfo.setAccoutfseId(AcountFSE);

      // AcountName
      String acountName = instrument_data_json.getString("AcountName") == null ? ""
          : instrument_data_json.getString("AcountName");
      serviceNotice.setAccoutfseName(acountName);
      instrumentInfo.setAccoutfseName(acountName);

      /** 服务单仪器子表 */
      if (serviceInstrumentList != null && serviceInstrumentList.size() > 0) {
        serviceInstrument.setId(serviceInstrumentList.get(0).getId());
        serviceInstrument.setUpdateTime(new Date());
        serviceInstrumentMapper.updateSyncServiceInstrument(serviceInstrument);
      } else {
        serviceInstrument.setCreateTime(new Date());
        serviceInstrumentMapper.insertServiceInstrument(serviceInstrument);
      }

      /** 仪器表 */
      if (instrumentInfoList != null && instrumentInfoList.size() > 0) {
        instrumentInfo.setId(instrumentInfoList.get(0).getId());
        instrumentInfo.setUpdateTime(new Date());
        instrumentInfoMapper.updateSyncInstrumentInfo(instrumentInfo);
      } else {

        /** 调用高德地理解析接口，根据地址解析经纬度 */
        Map<String, String> map = locationService.AddressResolution(InsAddress, "");
        if (map != null && map.size() == 2) {
          instrumentInfo.setLongitude(Double.parseDouble(map.get("longitude")));
          instrumentInfo.setLatitude(Double.parseDouble(map.get("latitude")));
        }

        instrumentInfo.setCreateTime(new Date());
        instrumentInfoMapper.insertInstrumentInfo(instrumentInfo);
      }

    }
  }

  private void parseAndUpdateServiceNoticePart(ServiceNotice serviceNotice, String part_data) {
    if (StringUtils.isNotEmpty(part_data) && !"[]".equals(part_data)) {
      JSONArray Part_data_jsonArray = JSON.parseArray(part_data);

      /** 先删除所有备件，然后在新增新的备件 */
      ServicePart sp = new ServicePart();
      sp.setServiceNoticeId(serviceNotice.getId());
      servicePartMapper.deleteServicePart(sp);

      for (int j = 0; j < Part_data_jsonArray.size(); j++) {
        JSONObject Part_data_json = Part_data_jsonArray.getJSONObject(j);
        ServicePart servicePart = new ServicePart();

        servicePart.setServiceNoticeId(serviceNotice.getId());
        servicePart.setServiceNo(serviceNotice.getServiceNo());

        // 备件号
        String Part_no = Part_data_json.getString("Part_no");
        servicePart.setPartNo(Part_no);

        // 备件名称
        String Part_name = Part_data_json.getString("Part_name");
        servicePart.setPartName(Part_name);

        // 序列号
        String serial_number = Part_data_json.getString("serial_number") == null ? ""
            : Part_data_json.getString("serial_number");
        servicePart.setSerialNumber(serial_number);

        // 借货单号
        String Part_DebitNo = Part_data_json.getString("Part_DebitNo") == null ? ""
            : Part_data_json.getString("Part_DebitNo");
        servicePart.setPartDebitNo(Part_DebitNo);

        // 数量
        String qty =
            Part_data_json.getString("qty") == null ? "" : Part_data_json.getString("qty");
        servicePart.setQty(qty);

        // 单价
        String Price = Part_data_json.getString("Price") == null ? ""
            : Part_data_json.getString("Price");
        servicePart.setPrice(Price);

        // 总价
        String TotalPrice = Part_data_json.getString("TotalPrice") == null ? ""
            : Part_data_json.getString("TotalPrice");
        servicePart.setTotalPrice(TotalPrice);

        // 备注
        String remark = Part_data_json.getString("remark") == null ? ""
            : Part_data_json.getString("remark");
        servicePart.setRemark(remark);

        // partremark
        String partremark = Part_data_json.getString("partremark") == null ? ""
            : Part_data_json.getString("partremark");
        servicePart.setPartremark(partremark);

        servicePart.setCreateTime(new Date());

        // 保存服务单关联备件
        servicePartMapper.insertServicePart(servicePart);

      }

    }
  }

  /**
   * 待指派
   * @param Fses
   * @param list
   * @param serviceNoticeId
   * @param serviceNo
   * @param teamleaderName
   * @param canPushMsg
   */
  private void insertDaiZhiPai(String[] Fses, List<String> list, String serviceNoticeId,
      String serviceNo, String teamleaderName, boolean canPushMsg) {
    if (Fses != null && Fses.length > 0) {
      for (String fse : Fses) {
        // TODO 有指派的人生成派单数据
        if (StringUtils.isNotEmpty(fse)) {

          // 验证数据库中是否存在数据
          ServiceDetails serviceDetails1 = new ServiceDetails();
          serviceDetails1.setServiceNo(serviceNo);
          serviceDetails1.setFseId(fse);
          List<ServiceDetails> serviceDetailsList = serviceDetailsMapper
              .selectServiceDetailsList(serviceDetails1);
          // 如果存在按照恢复处理
          if (serviceDetailsList != null && serviceDetailsList.size() > 0) {
            ServiceDetails serviceDetails2 = new ServiceDetails();
            serviceDetails2.setDelFlag("0");
            serviceDetails2.setServiceNo(serviceNo);
            serviceDetails2.setFseId(fse);
            serviceDetailsMapper.updateDelServiceDetails(serviceDetails2);

            PlanDetails planDetails2 = new PlanDetails();
            planDetails2.setDelFlag("0");
            planDetails2.setServiceNo(serviceNo);
            planDetails2.setFseId(fse);
            planDetailsMapper.updateDelPlanDetail(planDetails2);
            continue;
          }

          User user = new User();
          user.setEnginnerId(Long.parseLong(fse));
          List<User> users = userMapper.selectUserList(user);
          PlanDetails planDetails = new PlanDetails();
          ServiceDetails serviceDetails = new ServiceDetails();
          if (users != null && users.size() > 0) {
            planDetails.setFseName(users.get(0).getName());
            serviceDetails.setFseName(users.get(0).getName());

            planDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
            planDetails.setServiceNo(serviceNo);
            planDetails.setFseId(fse);
            planDetails.setIsAccept("2");
            planDetails.setState("0");
            planDetails.setDelFlag("0");
            planDetails.setCreateTime(new Date());
            planDetailsMapper.insertStPlanDetails(planDetails);

            serviceDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
            serviceDetails.setServiceNo(serviceNo);
            serviceDetails.setFseId(fse);
            serviceDetails.setState(0L);
            serviceDetails.setDelFlag("0");
            serviceDetails.setCreateTime(new Date());
            serviceDetails.setUpdateBy(planDetails.getId() + "");
            serviceDetailsMapper.insertServiceDetails(serviceDetails);

            if (canPushMsg) {
              // TODO 如果推送标识有值 推送给TL
              if (StringUtils.isNotEmpty(teamleaderName) && StringUtils
                  .isNotEmpty(users.get(0).getRegistrationId())) {
                // fse 待接受推送
                this.pushDaiJieShou(serviceNoticeId, serviceNo, fse,
                    users.get(0).getRegistrationId(),
                    planDetails.getId() + "", teamleaderName);
              }
            }
          } else {
            //本地表没有当前fse 存入数据 不推送
            planDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
            planDetails.setServiceNo(serviceNo);
            planDetails.setFseId(fse);
            planDetails.setIsAccept("2");
            planDetails.setState("0");
            planDetails.setDelFlag("0");
            planDetails.setCreateTime(new Date());
            planDetailsMapper.insertStPlanDetails(planDetails);

            serviceDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
            serviceDetails.setServiceNo(serviceNo);
            serviceDetails.setFseId(fse);
            serviceDetails.setState(0L);
            serviceDetails.setDelFlag("0");
            serviceDetails.setCreateTime(new Date());
            serviceDetails.setUpdateBy(planDetails.getId() + "");
            serviceDetailsMapper.insertServiceDetails(serviceDetails);
          }
        }
      }
    }
    if (list != null && list.size() > 0) {
      for (String fse : list) {

        // 验证数据库中是否存在数据
        ServiceDetails serviceDetails1 = new ServiceDetails();
        serviceDetails1.setServiceNo(serviceNo);
        serviceDetails1.setFseId(fse);
        List<ServiceDetails> serviceDetailsList = serviceDetailsMapper
            .selectServiceDetailsList(serviceDetails1);
        // 如果存在按照恢复处理
        if (serviceDetailsList != null && serviceDetailsList.size() > 0) {
          ServiceDetails serviceDetails2 = new ServiceDetails();
          serviceDetails2.setDelFlag("0");
          serviceDetails2.setServiceNo(serviceNo);
          serviceDetails2.setFseId(fse);
          serviceDetailsMapper.updateDelServiceDetails(serviceDetails2);

          PlanDetails planDetails2 = new PlanDetails();
          planDetails2.setDelFlag("0");
          planDetails2.setServiceNo(serviceNo);
          planDetails2.setFseId(fse);
          planDetailsMapper.updateDelPlanDetail(planDetails2);
          continue;
        }

        User user = new User();
        user.setEnginnerId(Long.parseLong(fse));
        List<User> users = userMapper.selectUserList(user);
        PlanDetails planDetails = new PlanDetails();
        ServiceDetails serviceDetails = new ServiceDetails();
        if (users != null && users.size() > 0) {
          planDetails.setFseName(users.get(0).getName());
          serviceDetails.setFseName(users.get(0).getName());

          planDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
          planDetails.setServiceNo(serviceNo);
          planDetails.setFseId(fse);
          planDetails.setIsAccept("2");
          planDetails.setState("0");
          planDetails.setDelFlag("0");
          planDetails.setCreateTime(new Date());
          planDetailsMapper.insertStPlanDetails(planDetails);

          serviceDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
          serviceDetails.setServiceNo(serviceNo);
          serviceDetails.setFseId(fse);
          serviceDetails.setState(0L);
          serviceDetails.setDelFlag("0");
          serviceDetails.setCreateTime(new Date());
          serviceDetails.setUpdateBy(planDetails.getId() + "");
          serviceDetailsMapper.insertServiceDetails(serviceDetails);

          if (canPushMsg) {
            // TODO 如果推送标识有值 推送给TL
            if (StringUtils.isNotEmpty(teamleaderName) && StringUtils
                .isNotEmpty(users.get(0).getRegistrationId())) {
              // fse 待接受推送
              this.pushDaiJieShou(serviceNoticeId, serviceNo, fse, users.get(0).getRegistrationId(),
                  planDetails.getId() + "", teamleaderName);
            }
          }
        } else {
          planDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
          planDetails.setServiceNo(serviceNo);
          planDetails.setFseId(fse);
          planDetails.setIsAccept("2");
          planDetails.setState("0");
          planDetails.setDelFlag("0");
          planDetails.setCreateTime(new Date());
          planDetailsMapper.insertStPlanDetails(planDetails);

          serviceDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
          serviceDetails.setServiceNo(serviceNo);
          serviceDetails.setFseId(fse);
          serviceDetails.setState(0L);
          serviceDetails.setDelFlag("0");
          serviceDetails.setCreateTime(new Date());
          serviceDetails.setUpdateBy(planDetails.getId() + "");
          serviceDetailsMapper.insertServiceDetails(serviceDetails);
        }
      }
    }
  }

  /**
   * 待接受消息推送
   *
   * @methodName: pushDaiJieShou
   * @description: TODO
   * @return: void
   * @author: wyl
   * @date: 2020-06-26 15:00
   **/
  private void pushDaiJieShou(String serviceNoticeId, String serviceNo, String fse,
      String registrationId, String planId, String teamleaderName) {
    ServiceNotice serviceNotic = new ServiceNotice();
    serviceNotic.setServiceNo(serviceNo);
    List<ServiceNotice> serviceNoticeList = serviceNoticeMapper.selectServiceNoticeList(serviceNotic);
    if (serviceNoticeList.size() > 0) {
      ServiceNotice serviceNotice = serviceNoticeList.get(0);
      if (serviceNotice.getTeamleaderId() != null) {

        String content = PushConfig.ACCEPT_CONTENT.replaceAll("NAME", teamleaderName).replaceAll("NO", serviceNo);
        // 推送额外参数
        JsonObject extra1 = new JsonObject();
        extra1.addProperty("type", PushConfig.ACCEPT_STATE);
        extra1.addProperty("serviceNoticeId", serviceNoticeId);
        extra1.addProperty("serviceNo", serviceNo);
        extra1.addProperty("planId", planId);

        JpushLog jpushLog1 = new JpushLog();
        PushResult pushResult1 = null;
        try {
          JPushClientUtil.getInstance()
              .initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
          pushResult1 = JPushClientUtil.getInstance()
              .sendPush(registrationId, PushConfig.ACCEPT_TITLE, content, extra1);
          System.out.println(pushResult1);
          jpushLog1.setStatuscode(pushResult1.statusCode + "");
          jpushLog1.setMsgId(pushResult1.msg_id + "");
          jpushLog1.setSendno(pushResult1.sendno + "");
        } catch (APIConnectionException e) {
          // Connection error, should retry later
          log.error("Connection error, should retry later", e);
          jpushLog1.setMessage("APIConnectionException:" + e.getMessage());
        } catch (APIRequestException e) {
          // Should review the error, and fix the request
          log.error("Should review the error, and fix the request", e);
          log.info("HTTP Status: " + e.getStatus());
          log.info("Error Code: " + e.getErrorCode());
          log.info("Error Message: " + e.getErrorMessage());
          jpushLog1.setStatuscode(e.getErrorCode() + "");
          jpushLog1.setMessage(e.getStatus() + "," + e.getErrorMessage());
        }
        // 保存推送日志
        jpushLog1.setEnginnerId(fse);
        jpushLog1.setType(PushConfig.ONE_PUSH);
        jpushLog1.setRegistrationId(registrationId);
        jpushLog1.setState(PushConfig.ACCEPT_STATE);
        jpushLog1.setNoticeId(Long.parseLong(serviceNoticeId));
        jpushLog1.setServiceNo(serviceNo);
        jpushLog1.setPlanId(Long.parseLong(planId));
        jpushLog1.setTitle(PushConfig.ACCEPT_TITLE);
        jpushLog1.setContent(content);
        jpushLog1.setExtra(extra1.toString());
        jpushLog1.setPushTime(new Date());
        jpushLog1.setCreateTime(new Date());
        jpushLogMapper.insertJpushLog(jpushLog1);
      }
    }
  }

  /**
   * TL消息推送
   *
   * @methodName: pushTeamleader
   * @description: TODO
   * @author: wyl
   * @date: 2020-06-26 15:00
   * @date: 2020-04-20 13:24
   **/
  private void pushTeamleader(String serviceNoticeId, String serviceNo, String teamleaderId,
      String registrationId) {
    // 推送额外参数
    JsonObject extra = new JsonObject();
    extra.addProperty("type", PushConfig.DISPATCHED_WORKER_STATE);
    extra.addProperty("serviceNoticeId", serviceNoticeId);
    extra.addProperty("serviceNo", serviceNo);
    extra.addProperty("teamleaderId", teamleaderId);

    JpushLog jpushLog = new JpushLog();
    PushResult pushResult = null;
    try {
      JPushClientUtil.getInstance()
          .initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
      pushResult = JPushClientUtil.getInstance()
          .sendPush(registrationId, PushConfig.DISPATCHED_WORKER_TITLE,
              PushConfig.DISPATCHED_WORKER_CONTENT.replaceAll("NO", serviceNo), extra);

      jpushLog.setStatuscode(pushResult.statusCode + "");
      jpushLog.setMsgId(pushResult.msg_id + "");
      jpushLog.setSendno(pushResult.sendno + "");
    } catch (APIConnectionException e) {
      // Connection error, should retry later
      log.error("Connection error, should retry later", e);
      jpushLog.setMessage("APIConnectionException:" + e.getMessage());
    } catch (APIRequestException e) {
      // Should review the error, and fix the request
      log.error("Should review the error, and fix the request", e);
      log.info("HTTP Status: " + e.getStatus());
      log.info("Error Code: " + e.getErrorCode());
      log.info("Error Message: " + e.getErrorMessage());
      jpushLog.setStatuscode(e.getErrorCode() + "");
      jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
    }
    // 保存推送日志
    jpushLog.setEnginnerId(teamleaderId);
    jpushLog.setType(PushConfig.ONE_PUSH);
    jpushLog.setRegistrationId(registrationId);
    jpushLog.setState(PushConfig.DISPATCHED_WORKER_STATE);
    jpushLog.setNoticeId(Long.parseLong(serviceNoticeId));
    jpushLog.setServiceNo(serviceNo);
    jpushLog.setTitle(PushConfig.DISPATCHED_WORKER_TITLE);
    jpushLog.setContent(PushConfig.DISPATCHED_WORKER_CONTENT.replaceAll("NO", serviceNo));
    jpushLog.setExtra(extra.toString());
    jpushLog.setPushTime(new Date());
    jpushLog.setCreateTime(new Date());
    jpushLogMapper.insertJpushLog(jpushLog);
  }

  @Override
  public ResponseWithData<?> syncServiceNoticeTest(String interfaceResponseBody) throws Exception {

    JSONObject obj = JSON.parseObject(interfaceResponseBody);
    if ("1".equals(obj.getString("status"))) {

      /** 获取CC端 */
      JSONArray jsonArray = obj.getJSONArray("record");
      if (jsonArray != null && jsonArray.size() > 0) {
        for (int i = 0; i < jsonArray.size(); i++) {
          JSONObject jsonObject = jsonArray.getJSONObject(i);

          //解析同步过来的数据
          ServiceNotice serviceNotice = parseServiceNoticeRd(jsonObject);

          // 更新服务状态
          if ("TL派单".equals(serviceNotice.getServiceStatus())) {
            serviceNotice.setAppState(1L);//待派单
          }
          else if ("已派单".equals(serviceNotice.getServiceStatus())) {
          }
          else if ("保留".equals(serviceNotice.getServiceStatus())) {
          }
          else if ("已完成".equals(serviceNotice.getServiceStatus())) {
            //服务状态是已完成的修改服务单状态为已完成
            serviceNotice.setAppState(3L);//已完成 已关闭
          }
          if(StringUtils.equals("撤单",serviceNotice.getServiceStatus())){
            if(ObjectUtils.isEmpty(serviceNotice.getUpdateDate())){
              serviceNotice.setUpdateDate(new Date());
            }
          }
          /** 通过服务号验证数据库中是否存在 */
          ServiceNotice serviceNoticeOld = selectServiceNoticeByServieNo(serviceNotice.getServiceNo());

          if (serviceNoticeOld != null ) {
            serviceNotice.setId(serviceNoticeOld.getId());
            /** 服务单主表 如果存在更新 更新cc过来的数据*/
            serviceNoticeMapper.updateSyncServiceNotice(serviceNotice);
          }
          else {
            // 新增 服务单数据
            serviceNotice.setAppState(1L);
            serviceNotice.setRecordTime(new Date());
            serviceNoticeMapper.insertServiceNotice(serviceNotice);
          }

          //派单处理  TL派单发送消息提醒
          if ("TL派单".equals(serviceNotice.getServiceStatus())) {
            dealServiceNoticeTLPaiDan(serviceNotice);
          }

          //FSE派单 处理（TL重新派单，原有FSE任务保留，删除状态）
          dealServiceNoticeFSEPaiDan(serviceNotice);

          // 仪器信息
          String instrument_data = jsonObject.getString("instrument_data");
          parseAndUpdateServiceNoticeInstrument(serviceNotice, instrument_data);

          // 备件信息
          String Part_data = jsonObject.getString("Part_data");
          parseAndUpdateServiceNoticePart(serviceNotice, Part_data);

          //更新服务状态
          updateServiceStatus(serviceNotice, serviceNoticeOld);
        }
      }
      return new ResponseWithData().success().msg("同步成功").code(200);
    } else if ("2".equals(obj.getString("status"))) {
      //无数据
      return new ResponseWithData().success().msg("同步成功").code(200);
    }

    return new ResponseWithData<>().error().msg("同步失败").code(201);
  }

}
